/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package Clases;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ListIterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author JULIAN
 */
public class GuardaCompraBD extends HttpServlet {
   
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {

         HttpSession session_actual = request.getSession(true);

         Vector v = (Vector) session_actual.getAttribute("carrito");

         ListIterator itr = v.listIterator();
         PreparedStatement st= null;

         ObjetoProducto obj = new ObjetoProducto();
         SQL_Inserciones obj2 = new SQL_Inserciones();
         SQL_Consultas obj3 = new SQL_Consultas();

         if((String)session_actual.getAttribute("clientexi")=="noexiste"){
         obj2.setCident((String)session_actual.getAttribute("id_cliente"));
         obj2.setCnombres((String)session_actual.getAttribute("nombres_cliente"));
         obj2.setCapellidos((String)session_actual.getAttribute("apellidos_cliente"));
         obj2.setCtelefono((String)session_actual.getAttribute("telefono_cliente"));
         st=obj2.InsertCliente();
         st.executeUpdate();
                                                                        }

         obj2.setCodventa((String)session_actual.getAttribute("factura"));
         obj2.setIdemp((String)session_actual.getAttribute("id_vendedor"));
         obj2.setTpago((String)session_actual.getAttribute("id_pago"));
         obj2.setIdcaja((String)session_actual.getAttribute("caja"));
         obj2.setCident((String)session_actual.getAttribute("id_cliente"));
         obj2.setIva((String)session_actual.getAttribute("ivat"));
         obj2.setCostot((String)session_actual.getAttribute("costot"));
         obj2.setIdalm((String)session_actual.getAttribute("alma"));

         st =obj2.InsertVenta();
         st.executeUpdate();

          st.close();

        itr = v.listIterator();

        while(itr.hasNext()){
                  obj = (ObjetoProducto) itr.next();

           obj2.setIdproducto(obj.getidP());
           obj2.setCantidad(obj.getCantidadP());
           obj2.setPrecioU(obj.getPrecioP());
           st=obj2.InsertProducto();
           st.executeUpdate();
           st.close();
           st=obj2.RestaExistencia();
           st.executeUpdate();
                              }
           st.close();

           obj3.setId((String)session_actual.getAttribute("id_vendedor"));
           st=obj3.GetexisteVendedorDia();

           ResultSet resultado = st.executeQuery();

           if(!resultado.next()){
           st.close();
           st=obj2.Sumavendedor();
           st.executeUpdate();
                                }
           else{
           st.close();
           st=obj2.Incrementavendedor();
           st.executeUpdate();

           }



           //liberar sesion de variables

           session_actual.removeAttribute("tipo_pago");
           session_actual.removeAttribute("telefono_cliente");
           session_actual.removeAttribute("nombres_cliente");
           session_actual.removeAttribute("ivat");
           session_actual.removeAttribute("id_vendedor");
           session_actual.removeAttribute("id_pago");
           session_actual.removeAttribute("fechabd");
           session_actual.removeAttribute("factura");
           session_actual.removeAttribute("costot");
           session_actual.removeAttribute("clientexi");
           session_actual.removeAttribute("carrito");
           session_actual.removeAttribute("apellidos_cliente");
           session_actual.removeAttribute("tipo_pago");
           session_actual.removeAttribute("id_cliente");
           response.sendRedirect("Venta.jsp");


        } finally { 
            out.close();
        }
    } 

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(GuardaCompraBD.class.getName()).log(Level.SEVERE, null, ex);
        }
    } 

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SQLException ex) {
            Logger.getLogger(GuardaCompraBD.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}
